package com.mtao.controller.admin;

import com.mtao.*;
import com.mtao.config.CacheConfig;
import com.mtao.constant.CaptchaConstants;
import com.mtao.dto.UserDto;
import com.mtao.dto.WxDto;
import com.mtao.exception.BadRequestException;
import com.mtao.utils.JwtUtils;
import com.mtao.utils.StringUtil;
import com.mtao.utils.WxUtil;
import com.mtao.entity.SysUser;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.base.Captcha;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @program: ems-admin-boot
 * @description: this is a class
 * @author: starao
 * @create: 2021-11-27 14:08
 **/
@RestController
@RequiredArgsConstructor
@RequestMapping("/auth")
public class LoginController{


    private final SysUserService userService;
    private final AuthenticationManagerBuilder authenticationManagerBuilder;

    @Resource
    private SysRoleService roleService;

    @Resource
    private LoginService loginService;

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private  WxUtil wxUtil;

    @Resource
    private CacheConfig cacheConfig;

    /**
     * @Description: 获取验证码
     * @Param: []
     * @return: org.springframework.http.ResponseEntity<java.lang.Object>
     * @Author: starao
     * @Date: 2022/1/18
     */
    @PostMapping("/code")
    public com.mtao.entity.Result getVerifyCode() {
        try {
            // 获取运算的结果
            Captcha captcha = new ArithmeticCaptcha(CaptchaConstants.width, CaptchaConstants.height);
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //当验证码类型为 arithmetic时且长度 >= 2 时，captcha.text()的结果有几率为浮点型
            String captchaValue = captcha.text();
            if (captchaValue.contains(".")) {
                captchaValue = captchaValue.split("\\.")[0];
            }
            // 缓存验证码信息,时间1分钟
            cacheConfig.put(uuid, captchaValue, 1);
            // 验证码信息
            Map<String, Object> imgResult = new HashMap<String, Object>(2) {{
                put("img", captcha.toBase64());
                put("uuid", uuid);
            }};
            return com.mtao.entity.Result.success(imgResult);
        } catch (BadRequestException e) {
            e.printStackTrace();
            return com.mtao.entity.Result.error(e.getMsg());
        }
    }

    /**
     * 登录
     *
     * @param userDto
     * @param request
     * @return
     */

    @PostMapping("/login")
    public com.mtao.entity.Result login(@RequestBody UserDto userDto, HttpServletRequest request) {
        try {
//            //  验证码为空
            if (StringUtil.isBlank(userDto.getCode())) {
                return com.mtao.entity.Result.error("验证码不能为空");
            }
            //  校验验证码
            if (StringUtil.isBlank(userDto.getCode()) || !checkCode(userDto.getUuid(), userDto.getCode())) {
                return com.mtao.entity.Result.error("验证码错误");
            }
            //  根据用户名查询用户是否存在
            SysUser user = userService.findByName(userDto.getUsername());
            if (user == null) {
                return com.mtao.entity.Result.error("用户名或密码错误");
            }
            if (!user.getEnabled()) {
                return com.mtao.entity.Result.error("当前账号已被停用");
            }
            //  判断密码是否正确
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(userDto.getUsername(), userDto.getPassword());
            Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
            //  将认证信息设置到SpringSecurity上下文中
            SecurityContextHolder.getContext().setAuthentication(authentication);
            HashMap login = loginService.login(userDto,user);
            return com.mtao.entity.Result.success(login);
        } catch (BadRequestException e){
            e.printStackTrace();
            System.out.println("e"+e.getMsg());
            return com.mtao.entity.Result.error(e.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("e"+e.getMessage());
            return com.mtao.entity.Result.error(e.getMessage());
        }
    }

    /**
     * 微信登录
     * @param wxDto
     */
    @PostMapping("/wx/login")
    private com.mtao.entity.Result wxLogin(@RequestBody WxDto wxDto){
//        String accessToken = wxUtil.getAccessToken();
//        System.out.println(accessToken);
//        wxDto.setAccessToken(accessToken);
        String openId = wxUtil.getOpenId(wxDto);
        System.out.println(openId);

        return com.mtao.entity.Result.success(openId);
    }



    /**
     * @Description: 用户注册
     * @Param: [userDto]
     * @return: org.springframework.http.ResponseEntity<java.lang.Object>
     * @Author: starao
     * @Date: 2021/11/27
     */
//    @Log("用户注册")
//    @PostMapping("/register")
//    public ResponseEntity<Object> registerUser(@RequestBody UserDto userDto){
//        try {
//            userService.editUser(userDto);
//            return success(true, "注册成功");
//        } catch (BadRequestException e) {
//            e.printStackTrace();
//            return fail(false, e.getMsg());
//        }
//    }

    /**
     * @Description: 通过refreshToken得到新的token
     * @Param: [request]
     * @return: org.springframework.http.ResponseEntity<java.lang.Object>
     * @Author: starao
     * @Date: 2022/10/5
     */
//    @PutMapping("/refresh")
//    public ResponseEntity<Object> refreshToken(HttpServletRequest request){
//        try {
//            //  通过请求头获取refreshToken
//            String refreshToken = request.getHeader(SecurityConstants.TOKEN_HEADER);
//            // 如果refreshToken存在
//            if (StringUtil.isNotBlank(refreshToken)){
//                //  去掉头部，得到原始refreshToken
//                refreshToken = refreshToken.replaceFirst(SecurityConstants.TOKEN_PREFIX, "");
//                //  解析refreshToken,得到用户名
//                Claims claims = JwtUtil.getRefreshTokenBody(refreshToken);
//                System.out.println(claims.getSubject());
//                //  如果refreshToken还在有效期内
//                if (claims.get("exp", Long.class) > 0){
//                    //  获取当前用户信息
//                    SysUser user = userService.findByName(claims.getSubject());
//                    //  获取当前用户角色
//                    List<String> roles = getRolesByUserId(user.getId());
//                    //  重新获取token
//                    String token = JwtUtil.generateToken(user.getUsername(), roles, false);
//                    return success(true, token);
//                }
//            }
//        } catch (BadRequestException e) {
//            return fail(false, e.getMsg());
//        }
//        return fail(false, "请重新登录");
//    }



    /**
     * @Description: 验证码校验
     * @Param: [uuid, code]
     * @return: boolean
     * @Author: starao
     * @Date: 2023/7/9
     */
    private boolean checkCode(String uuid, String code) {
        boolean b = false;
        if (cacheConfig.get(uuid) != null && cacheConfig.get(uuid).equals(code)) {
            b = true;
            cacheConfig.invalidate(uuid);
        }
        return b;
    }


}
